package com.nullyb.springbootshardingjdbc.algorithm;

import com.alibaba.fastjson.JSON;
import com.nullyb.springbootshardingjdbc.enums.Databases;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;

/**
 * 分库算法
 *  = 或 IN
 */
@Slf4j
public class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {

        log.info("collection:" + JSON.toJSONString(collection)+",PreciseShardingValue:" + JSON.toJSONString(preciseShardingValue));
        for (String database: collection) {
            String shardingVale = preciseShardingValue.getValue();
            if(Databases.getDatabaseName(shardingVale).equals(database)){
                log.info("databaseName:" + database);
                return database;
            }
        }
        throw new RuntimeException("路由数据库失败！");
    }
}
